package com.njiandan.android;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;

import com.njiandan.android.api.LocationApi;
import com.njiandan.android.bean.BaseBean;
import com.njiandan.android.utils.RetrofitUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;


public class CameraActivity extends Activity {
    private SurfaceView picSV;
    private Camera camera;
    private LocationApi mLocationApi;

    int _front_camera_index = -1;
    int _back_camera_index = -1;
    int _currentCameraIndex = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLocationApi = RetrofitUtils.createApi(this, LocationApi.class, BuildConfig.API_SERVER_URL);
        try {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            Window window = getWindow();
            WindowManager.LayoutParams wl = window.getAttributes();
            wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
            wl.alpha = 0.6f;   //这句就是设置窗口里崆件的透明度的．０.０全透明．１.０不透明．
            window.setAttributes(wl);


            setContentView(R.layout.activity_camera);

            picSV = (SurfaceView) findViewById(R.id.picSV);


            int cameraCount = Camera.getNumberOfCameras();
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();

            for (int i = 0; i < cameraCount; i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)
                    _back_camera_index = i;
                else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
                    _front_camera_index = i;
            }
            _currentCameraIndex = _back_camera_index;

            Bundle bundle = this.getIntent().getExtras();
            boolean isChecked = bundle.getBoolean("isUseFrontFacingCamera");
            _currentCameraIndex = isChecked ? _front_camera_index : _back_camera_index;


            picSV.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            picSV.getHolder().addCallback(new MyCallback());
        } catch (Exception e) {
            e.printStackTrace();

            finish();
        }
    }


    private class MyCallback implements Callback {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {		//我们在SurfaceView创建的时候就要进行打开摄像头、设置预览取景所在的SurfaceView、设置拍照的参数、开启预览取景等操作
            try {
                if (camera == null) {
                    try {
                        camera = Camera.open(_currentCameraIndex);                //打开摄像头
                    } catch (Exception e) {
                        return;
                    }
                }

                camera.setPreviewDisplay(picSV.getHolder());	//设置picSV来进行预览取景

                Camera.Parameters params = camera.getParameters();	//获取照相机的参数
//                params.setPictureSize(800, 600);		//设置照片的大小为800*480
//                params.setPreviewSize(800, 600);		//设置预览取景的大小为800*480
                params.setFlashMode("off");			//关闭闪光灯
                params.setJpegQuality(60);			//设置图片质量为50

                int cameraPictureRotation;
                if (_currentCameraIndex == _back_camera_index) {
                    cameraPictureRotation = 90;
                    //params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                } else {
                    cameraPictureRotation = 270;
                }
                params.setRotation(cameraPictureRotation);

                camera.setParameters(params);			//设置以上参数为照相机的参数
                camera.startPreview();


                tackpic();
            } catch (IOException e) {				//开始预览取景，然后我们就可以拍照了
                e.printStackTrace();
            }
        }
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {		//当SurfaceView销毁时，我们进行停止预览、释放摄像机、垃圾回收等工作
            camera.stopPreview();
            camera.release();
            camera = null;
        }

    }
    public void tackpic() {
        try {
            camera.autoFocus(new MyAutoFocusCallback());            //在我们开始拍照前，实现自动对焦
        } catch (Exception e) {
            e.printStackTrace();

            finish();
        }
    }

    private class MyAutoFocusCallback implements Camera.AutoFocusCallback {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            try {
                camera.takePicture(null, null, null, new MyPictureCallback());		//开始拍照
            } catch (Exception e) {
                e.printStackTrace();

                finish();
            }
        }

    }



    private class MyPictureCallback implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {	//将拍摄到的图片放到"/mnt/sdcard/DCIM/Camera/"这个文件夹中
            try {
                String path = Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera/"+System.currentTimeMillis()+".jpg";
                FileOutputStream fos = new FileOutputStream(path);
                fos.write(data);
                fos.close();
//                camera.startPreview();

                // 上传图片
                File file = new File(path);
                String mimeType = "image/jpg";
                TypedFile fileToSend = new TypedFile(mimeType, file);
                TypedString installationId = new TypedString(AppContext.InstallationId);
                mLocationApi.uploadFile(fileToSend, installationId, new BaseBeanCallbak(path));
            } catch (Exception e) {
                e.printStackTrace();
            }

            finish();
        }

        public class BaseBeanCallbak implements retrofit.Callback<BaseBean> {
            String mPicPath;
            public BaseBeanCallbak(String picPath) {
                mPicPath = picPath;
            }

            @Override
            public void success(BaseBean baseBean, Response response) {
                deleteFile(new File(mPicPath));
            }

            @Override
            public void failure(RetrofitError error) {
                deleteFile(new File(mPicPath));
            }

            public void deleteFile(File file) {
                try {
                    if (file.exists()) { // 判断文件是否存在
                        if (file.isFile()) { // 判断是否是文件
                            file.delete(); // delete()方法 你应该知道 是删除的意思;
                        } else if (file.isDirectory()) { // 否则如果它是一个目录
                            File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                            for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                                this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                            }
                        }
                        file.delete();
                    } else {

                    }
                } catch (Exception e) {

                }
            }
        }





    }
}
